
import Vapi from "vuex-rest-api"
import Vue from 'vue'
import Axios from 'axios'
import config  from '../config/config'
import defaultState from './state'
import moment from 'moment'
import {FORMAT_STRING} from '../views/commons/tools'
import _ from 'lodash'

const baseURL = config.server || '/api';

const axios = Axios.create({
  baseURL: baseURL,
  timeout: 1000
});

const api = new Vapi({
    baseURL: baseURL
})
.get({
    action: "getUsers",
    property: "users",
    path: () => `/users`
  })
.get({
    action: "getCurrentUserSatistics",
    property:'userSatistics',
    path: ()=>'/satistics/currentUser',
})
.get({
    action: "getTotalHours",
    property: "project.totalHours",
    path: () => `/satistics/totalHours`,
    onSuccess: (state, payload) => {
        // if you set the onSuccess function you have to set the state manually
        state.project.totalHours = payload.data.totalHours
    }
  })
.get({
    action: "getCurrentUser",
    property: "user",
    path: () => `/user`,
    onSuccess: (state, payload) => {
        // if you set the onSuccess function you have to set the state manually
        state.user.name = payload.data.loginname;
        state.user.nickname = payload.data.nick_name;
        state.user.avatar = payload.data.avatar_src;
        
    }
  })

const store = api.getStore();

export default store

const mutations = {

    setShowEditCard(state, isShow){
        state.showEditCard = isShow;
    },

    setShowAdvanceFilter(state, isShow){
        state.showAdvanceFilter = isShow;
    },

    addLog(state, log){
        state.logs.unshift(log);
    },

    setCurrentScene(state, scene){
        state.currentScene = scene;
    },

    setEditData(state, log){
        var obj = Object.assign({},log);
        if(obj.labels){
            obj.labels = obj.labels.map(a=>a);
        }
        if(obj.timerange){
            obj.timerange = obj.timerange.map(a=>a);
        }
        state.editData = obj;
    }
}



store.state = Object.assign(store.state, defaultState);
store.mutations = Object.assign(store.mutations, mutations);
store.getters = Object.assign(store.getters||{}, {
    logList: state => state.logs.data,
    groupedLogs: function(state){
        let result =  _.chain(state.logs.data).sortBy('create_at').reverse().groupBy(function(item){
                    return moment(item.day).format(FORMAT_STRING);
                }).map(function(logs, key){
                    return {
                        day: key,
                        logs: logs,
                    };
                }).sortBy('day')
                .reverse()
                .value();
        return result;
    }
})

function getQueryUrl(state, head){
    
    var c = state.conditionable?
            _.chain(state.conditions)
             .filter(condition=>condition.value)
             .reduce((result, condition)=>{
                return result+`&${condition.field}${condition.predicate}${condition.value}`
            },'').value()
            :'';

    return `/logs?sort=-day,-create_at&pageSize=${state.logs.pageSize}&page=${head?0:(state.logs.page+1)}&scene=${state.currentScene}${c}`;
}

store.actions = Object.assign(store.actions,{
    listLogs({commit, state, dispatch}){
        axios.get(getQueryUrl(state, true))
        .then(function (response) {
            state.logs = response.data;
        })
        .catch(function (error) {
            Vue.prototype.$Message.error('获取日志数据失败');
        });
    },
    refresh({commit, state, dispatch}){

        dispatch('listLogs');
        dispatch('getTotalHours');
        dispatch('getCurrentUserSatistics');
    },
    postLog ({commit, state, dispatch}, log){
        let error = false;
        if(!log.content){
            Vue.prototype.$Notice.error({
                desc: '请输入工作内容',
            });
            error = true;
        }
        if(!log.duration){
            Vue.prototype.$Notice.error({
                desc: '请输入工作时长',
            });
            error = true;
        }
        if(error){
            return;
        }

        if(log._id){
            axios.put('/logs/'+log._id, Object.assign({},log,{
                user: state.user.name
            }))
            .then(function (response) {
                Vue.prototype.$Message.success('更新成功');
                log.labels = [];
                log.content = '';

                dispatch('refresh');

                state.showEditCard = false;
            })
            .catch(function (error) {
                Vue.prototype.$Message.error('更新失败');
            });
        } else {
            axios.post('/logs', Object.assign({},log,{
                user: state.user.name
            }))
            .then(function (response) {
                Vue.prototype.$Message.success('添加成功');
                log.labels = [];
                log.content = '';
                // log.duration = '';

                dispatch('refresh');
            })
            .catch(function (error) {
                Vue.prototype.$Message.error('添加失败');
            });
        }
        

    },
    deleteLog({commit, state, dispatch}, log){
        if(!(log && log._id)){
            Vue.prototype.$Notice.error('无法删除');
            return
        }
        axios.delete('/logs/'+log._id)
        .then(function (response) {
            Vue.prototype.$Message.success('删除成功');
            dispatch('refresh');
        })
        .catch(function (error) {
            Vue.prototype.$Message.error('删除失败');
        });
    },
    moreLogs({commit, state, dispatch}){
        axios.get(getQueryUrl(state))
        .then(function (response) {
            Vue.prototype.$Message.success('加载成功');
            if(response.data.data.length > 0){
                //filter response data
                var map = _.reduce(state.logs.data, function(result, value) {
                     result[value._id] = value;
                     return result;
                }, {});

                var filteredData = _.filter(response.data.data, function(value){
                    return !map[value._id];
                });

                state.logs.data = state.logs.data.concat(filteredData);
                state.logs.page = Number(response.data.page);
                state.logs.pageSize = response.data.pageSize;
            } else {
                Vue.prototype.$Message.info('没有更多啦');
            }
            
        })
        .catch(function (error) {
            Vue.prototype.$Message.error('加载失败');
        });
    },
    filterByUser({commit, state, dispatch}, user){
        state.conditions[0].value = user;
        state.conditionable = true;
        dispatch('listLogs');
    }
});
